package cn.com.headfree.deptuser.controller;

import cn.com.headfree.base.controller.ExBaseController;
import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.base.initData.InitData;
import cn.com.headfree.entity.TOrgDept;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.mouldshow.service.TEmpBaseInfoService;
import cn.com.headfree.vo.*;
import com.gta.edu.sdk.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@CrossOrigin("*")
@RestController
@RequestMapping(value = "/deptAndUser", produces = "application/json;charset=UTF-8")
public class DeptAndUserController extends ExBaseController {
	private static final Logger LOG = LogManager.getLogger(DeptAndUserController.class);

	@Autowired
	private TEmpBaseInfoService tEmpBaseInfoService;

	/**
	 *
	 * @description 点击下级查询的接口
	 * @author 徐亮
	 * @date 2019年5月6日 上午10:52:38
	 * @param deptId 部门id
	 * @param deptName 部门名称
	 * @param userType 用户类型
	 * @return
	 * @return
	 * ResultData
	 */
	@RequestMapping("/getXjDeptListAndUser")
	@ResponseBody
	public ResultData getXjDeptListAndUser(HttpServletRequest request,String deptId, String deptName, String userType) {
		LOG.info("传入的参数deptId值为=================="+deptId);
		LOG.info("传入的参数deptName值为=================="+deptName);
		LOG.info("传入的参数userType值为=================="+userType);
		User user = new User();
		ResultData result=new ResultData();
		try{
			user = this.getLoginUserInfo(request);
			if(user == null || StringUtil.isNullOrEmpty(user.getPrivateIdentityId())){
				result.setErrorMsg("获取当前登录人失败");
				result.setSuccess(false);
				return result;
			}
		}catch (Exception e){
			e.printStackTrace();
			result.setSuccess(false);
			result.setErrorMsg("获取当前登录人失败");
			return result;
		}
		Object obj = InitData.getInstance().getData().get("DEPT_DATA");
		List<DeptUserNumDtoVo> list = null;
		DeptListVo deptListVo = new DeptListVo();
		String[] userTypes = null;
		List<UserVo> users=new ArrayList<UserVo>();
		Map<String,Object> deptD=new HashMap<String,Object>();
		try {
			if (obj != null) {
				deptD=(Map<String, Object>) obj;
				if(deptD!=null) {
					Object o=deptD.get("DEPT_CLASS_USER_NUM");
					Map<String, List<DeptUserNumVo>> deptClassMap = (Map<String, List<DeptUserNumVo>>)o ;
					Map<String,Object> deptData = (Map<String,Object>)deptClassMap.get(deptId);
					List<DeptUserNumVo> deptList = (List<DeptUserNumVo>)deptData.get("depts");
					List<UserVo> userList = (List<UserVo>)deptData.get("users");
					LOG.info("userList的值为==========================="+userList);
					Map<String,Set<UserVo>> deptUserMap =(Map<String, Set<UserVo>>) deptD.get("DEPT_USERS_SET");
					Set<UserVo> set=deptUserMap.get(deptId);
					//用来存放筛选过的用户
					Set<UserVo> userSet=new HashSet<UserVo>(set.size());
					deptListVo.setDeptId(deptId);
					deptListVo.setName(deptName);
					//满足选择的用户类型的用户
					if(!StringUtils.isBlank(userType)) {
						if("0".equals(userType)) {
							//"0"表示查询所有类型的用户
							users=userList;
							LOG.info("users的值为======================="+users);
							userSet=set;
						}else if("1".equals(userType)) {
							//1表示查询除信通公司员工外的所有外委人员
							for(int i=0;i<userList.size();i++) {
								UserVo userVo=userList.get(i);
								LOG.info("userVo的单个值为======================="+userVo);
								if(!("10000".equals(userVo.getUserType())) || StringUtils.isBlank(userVo.getUserType())) {//非信通员工或userType为空的
									users.add(userVo);
								}
							}
							for(UserVo u:set) {
								if(!("10000".equals(u.getUserType())) || StringUtils.isBlank(u.getUserType())) {
									userSet.add(u);
								}
							}
						}else {
							for(int i=0;i<userList.size();i++) {
								if (userType.contains(",")) {
									UserVo userVo=userList.get(i);
									userTypes = userType.split(",");
									for(String ut:userTypes) {
										if(ut.equals(userVo.getUserType())) {
											users.add(userVo);
										}
									}
								}else {
									UserVo userVo=userList.get(i);
									LOG.info("userVo的单个值为======================="+userVo);
									if(userType.equals(userVo.getUserType())) {
										users.add(userVo);
									}
								}
							}
							for(UserVo u:set) {
								if (userType.contains(",")) {
									userTypes = userType.split(",");
									for(String ut:userTypes) {
										if(ut.equals(u.getUserType())) {
											userSet.add(u);
										}
									}
								}else {
									if(userType.equals(u.getUserType())) {
										userSet.add(u);
									}
								}
							}
						}
					}else {
						users=userList;
						userSet=set;
					}
					deptListVo.setUserNum(userSet.size());
					if (deptList != null && deptList.size() > 0) {
						deptListVo.setHaveChildren(true);
						DeptUserNumDtoVo dto = null;
						list = new ArrayList<DeptUserNumDtoVo>(deptList.size());
						for (DeptUserNumVo vo : deptList) {
							Set<UserVo> s=deptUserMap.get(vo.getDeptId());
							Set<UserVo> usList=new HashSet<UserVo>();
							dto = new DeptUserNumDtoVo();
							dto.setDeptId(vo.getDeptId());
							dto.setDeptName(vo.getName());
							if (!StringUtils.isBlank(userType)) {
								if("0".equals(userType)) {
									usList=s;
								}else if("1".equals(userType)){
									for(UserVo u:s) {
										if(!("10000".equals(u.getUserType())) || StringUtils.isBlank(u.getUserType())) {
											usList.add(u);
										}
									}
								}else{
									for(UserVo u:s) {
										if (userType.contains(",")) {
											userTypes = userType.split(",");
											for(String ut:userTypes) {
												if(ut.equals(u.getUserType())) {
													usList.add(u);
												}
											}
										}else {
											if(userType.equals(u.getUserType())) {
												usList.add(u);
											}
										}
									}
								}
							}else {
								usList=s;
							}
							dto.setUserNum(usList.size());
							Map<String,Object> data = (Map<String,Object>)deptClassMap.get(vo.getDeptId());
							List<DeptUserNumVo> dataList = (List<DeptUserNumVo>)data.get("depts");
							List<UserVo> us = (List<UserVo>)data.get("users");
							List<UserVo> uss=new ArrayList<UserVo>();
							//筛选用户类型人员
							uss=getUserVosByUserType(userType,userTypes,us);
							if((dataList != null && dataList.size() > 0)||(uss!=null&&uss.size()>0)) {
								dto.setHaveChildren(true);
							}
							list.add(dto);
						}
					}
				}
			}
			//用来存放最终排过序的用户集合
			List<UserVo> finalUserVos=new ArrayList<UserVo>();
			//获取部门的主管对象集合
			List<UserVo> directors=this.getDirectors(deptId,users);
			//第一次排序，将部门主管按照既定顺序排序
			List<UserVo> directorUserVos=this.getFinalUserVosByOrder(directors,directors.size());
			//第二次排序，将剩余人员按照既定顺序排序
			users.removeAll(directors);
			//存放按照既定顺序排序以后的最终部门领导以外的员工的集合
			List<UserVo> notDirectorUserVos=this.getFinalUserVosByOrder(users,users.size());
			finalUserVos.addAll(directorUserVos);
			finalUserVos.addAll(notDirectorUserVos);
//			Properties p=(Properties) InitData.getInstance().getData().get("USER_TYPE");
			for(UserVo uv:finalUserVos) {
				String u=uv.getUserType();
				if(u!=null) {
					uv.setUserTypeName("信通员工");
				}
			}
			users.addAll(directors);
			deptListVo.setUserList(finalUserVos);
			deptListVo.setDeptlist(list);
			result.setSuccess(true);
			result.setData(deptListVo);
			LOG.info("结果数据为======================"+deptListVo);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorMsg("系统问题，请联系管理员！");
			e.printStackTrace();
		}
		LOG.info("返回数据为======================"+result);
		return result;
	}

	/**
	 *
	 * @description 点击上级查询的接口
	 * @author 徐亮
	 * @date 2019年5月6日 上午11:14:51
	 * @param deptId 部门Id
	 * @param userType 用户类型
	 * @return
	 * @return
	 * ResultData
	 */
	@RequestMapping("/getSjDeptListAndUser")
	@ResponseBody
	public ResultData getSjDeptListAndUser(String deptId,String userType) {
		Object obj = InitData.getInstance().getData().get("DEPT_DATA");
		List<DeptUserNumDtoVo> list = null;
		DeptListVo deptListVo = new DeptListVo();
		String[] userTypes = null;
		ResultData result=null;
		List<UserVo> users=new ArrayList<UserVo>();
		TOrgDept td=this.getTOrgDept(deptId);
		deptId=td.getpId()+"";
		try {
			if (obj != null) {
				Map<String,Object> deptD=(Map<String, Object>) obj;
				if(deptD!=null) {
					Object o=deptD.get("DEPT_CLASS_USER_NUM");
					Map<String, List<DeptUserNumVo>> deptClassMap = (Map<String, List<DeptUserNumVo>>)o ;
					Map<String,Object> deptData = (Map<String,Object>)deptClassMap.get(deptId);
					List<DeptUserNumVo> deptList = (List<DeptUserNumVo>)deptData.get("depts");
					List<UserVo> userList = (List<UserVo>)deptData.get("users");
					Map<String,Set<UserVo>> deptUserMap =(Map<String, Set<UserVo>>) deptD.get("DEPT_USERS_SET");
					Set<UserVo> set=deptUserMap.get(deptId);
					//用来存放筛选过的用户
					Set<UserVo> userSet=new HashSet<UserVo>(set.size());
					deptListVo.setDeptId(deptId);
					String deptName=this.getTOrgDept(deptId).getName();
					deptListVo.setName(deptName);
					//满足选择的用户类型的用户
					if(!StringUtils.isBlank(userType)) {
						if("0".equals(userType)) {
							//"0"表示查询所有类型的用户
							users=userList;
							userSet=set;
						}else if("1".equals(userType)) {
							//1表示查询除信通公司员工外的所有外委人员
							for(int i=0;i<userList.size();i++) {
								UserVo userVo=userList.get(i);
								LOG.info("userVo的单个值为======================="+userVo);
								if(!("10000".equals(userVo.getUserType())) || StringUtils.isBlank(userVo.getUserType())) {//非信通员工或userType为空的
									users.add(userVo);
								}
							}
							for(UserVo u:set) {
								if(!("10000".equals(u.getUserType())) || StringUtils.isBlank(u.getUserType())) {
									userSet.add(u);
								}
							}
						}else {
							for(int i=0;i<userList.size();i++) {
								if (userType.contains(",")) {
									UserVo userVo=userList.get(i);
									userTypes = userType.split(",");
									for(String ut:userTypes) {
										if(ut.equals(userVo.getUserType())) {
											users.add(userVo);
										}
									}
								}else {
									UserVo userVo=userList.get(i);
									if(userType.equals(userVo.getUserType())) {
										users.add(userVo);
									}
								}
							}
							for(UserVo u:set) {
								if (userType.contains(",")) {
									userTypes = userType.split(",");
									for(String ut:userTypes) {
										if(ut.equals(u.getUserType())) {
											userSet.add(u);
										}
									}
								}else {
									if(userType.equals(u.getUserType())) {
										userSet.add(u);
									}
								}
							}
						}
					}else {
						users=userList;
						userSet=set;
					}
					deptListVo.setUserNum(userSet.size());
					int num = 0;
					if (deptList != null && deptList.size() > 0) {
						deptListVo.setHaveChildren(true);
						DeptUserNumDtoVo dto = null;
						list = new ArrayList<DeptUserNumDtoVo>(deptList.size());
						for (DeptUserNumVo vo : deptList) {
							dto = new DeptUserNumDtoVo();
							Set<UserVo> s=deptUserMap.get(vo.getDeptId());
							//用来存放筛选过的用户
							Set<UserVo> usList=new HashSet<UserVo>();
							dto.setDeptId(vo.getDeptId());
							dto.setDeptName(vo.getName());
							if (!StringUtils.isBlank(userType)) {
								if("0".equals(userType)) {
									usList=s;
								}else if("1".equals(userType)){
									for(UserVo u:s) {
										if(!("10000".equals(u.getUserType())) || StringUtils.isBlank(u.getUserType())) {
											usList.add(u);
										}
									}
								}else{
									for(UserVo u:s) {
										if (userType.contains(",")) {
											userTypes = userType.split(",");
											for(String ut:userTypes) {
												if(ut.equals(u.getUserType())) {
													usList.add(u);
												}
											}
										}else {
											if(userType.equals(u.getUserType())) {
												usList.add(u);
											}
										}
									}
								}
							}else {
								usList=s;
							}
							dto.setUserNum(usList.size());
							Map<String,Object> data = (Map<String,Object>)deptClassMap.get(vo.getDeptId());
							List<DeptUserNumVo> dataList = (List<DeptUserNumVo>)data.get("depts");
							List<UserVo> us = (List<UserVo>)data.get("users");
							//筛选用户类型人员
							List<UserVo> uss=new ArrayList<UserVo>();
							uss=getUserVosByUserType(userType,userTypes,us);
							if((dataList != null && dataList.size() > 0)||(uss!=null&&uss.size()>0)) {
								dto.setHaveChildren(true);
							}
							list.add(dto);
						}
					}
				}
				//用来存放最终排过序的用户集合
				List<UserVo> finalUserVos=new ArrayList<UserVo>();
				//获取部门的主管对象集合
				List<UserVo> directors=this.getDirectors(deptId,users);
				//第一次排序，将部门主管按照既定顺序排序
				List<UserVo> directorUserVos=this.getFinalUserVosByOrder(directors,directors.size());
				//第二次排序，将剩余人员按照既定顺序排序
				users.removeAll(directors);
				//存放按照既定顺序排序以后的最终部门领导以外的员工的集合
				List<UserVo> notDirectorUserVos=this.getFinalUserVosByOrder(users,users.size());
//				Properties p=(Properties) InitData.getInstance().getData().get("USER_TYPE");
				finalUserVos.addAll(directorUserVos);
				finalUserVos.addAll(notDirectorUserVos);
				for(UserVo uv:finalUserVos) {
					String u=uv.getUserType();
					if(u!=null) {
						uv.setUserTypeName("信通员工");
					}
				}
				users.addAll(directors);
				deptListVo.setUserList(finalUserVos);
				deptListVo.setDeptlist(list);
				result = new ResultData();
				result.setSuccess(true);
				result.setData(deptListVo);
			}
		} catch (Exception e) {
			result.setSuccess(false);
			result.setErrorMsg("系统问题，请联系管理员！");
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 筛选出userVos集合里面的获取用户类型为userType的用户集合
	 * @description
	 * @author 徐亮
	 * @date 2019年5月10日 下午3:37:50
	 * @param userVos
	 * @param userType
	 * @return
	 * @return
	 * List<UserVo>
	 */
	private List<UserVo> getUserVosByUserType(List<UserVo> userVos,String userType) {
		List<UserVo> users=new ArrayList<UserVo>();
		for(UserVo userVo:userVos) {
			if(userType.equals(userVo.getUserType())) {
				users.add(userVo);
			}
		}
		return users;
	}

	/**
	 *
	 * @description 将用户集合按照给定顺序排序(信通、挂职、借调、一体化用工、运维、建设、临时、实习、其他)
	 * @author 徐亮
	 * @date 2019年5月10日 下午4:10:36
	 * @param users
	 * @param size
	 * @return
	 * @return
	 * List<UserVo>
	 */
	public List<UserVo> getFinalUserVosByOrder(List<UserVo> users,int size){
		List<UserVo> finalUserVosByOrder=new ArrayList<UserVo>(size);
		//获取信通员工集合
		List<UserVo> formatList=this.getUserVosByUserType(users,"10000");
		//获取挂职员工集合
		List<UserVo> taketList=this.getUserVosByUserType(users,"3");
		//获取借调员工集合
		List<UserVo> borrowList=this.getUserVosByUserType(users,"20002");
		//获取一体化用工员工集合
		List<UserVo> intergrationList=this.getUserVosByUserType(users,"20020");
		//获取运维员工集合
		List<UserVo> operationsList=this.getUserVosByUserType(users,"20014");
		//获取建设员工集合
		List<UserVo> constructionList=this.getUserVosByUserType(users,"20009");
		//获取临时员工集合
		List<UserVo> tempList=this.getUserVosByUserType(users,"8");
		//获取实习员工集合
		List<UserVo> internshipList=this.getUserVosByUserType(users,"7");
		//获取其他员工集合
		List<UserVo> otherList=this.getUserVosByUserType(users,"20044");
		finalUserVosByOrder.addAll(formatList);
		finalUserVosByOrder.addAll(taketList);
		finalUserVosByOrder.addAll(borrowList);
		finalUserVosByOrder.addAll(intergrationList);
		finalUserVosByOrder.addAll(operationsList);
		finalUserVosByOrder.addAll(constructionList);
		finalUserVosByOrder.addAll(tempList);
		finalUserVosByOrder.addAll(internshipList);
		finalUserVosByOrder.addAll(otherList);
		return finalUserVosByOrder;
	}

	/**
	 * 获取部门的主管对象的UserVo集合
	 * @description
	 * @author 徐亮
	 * @date 2019年5月10日 下午3:30:14
	 * @param deptId 部门的id
	 * @param users  部门的用户集合
	 * @return
	 * @return
	 * List<UserVo> 部门的主管对象的UserVo集合
	 */
	public List<UserVo> getDirectors(String deptId,List<UserVo> users){
		//获取部门的主管对象集合
		List<UserVo> directors=new ArrayList<UserVo>();
		//获取部门id为deptId的部门对象
		TOrgDept td=this.getTOrgDept(deptId);
		//存放最终排过序的人员集合
		List<UserVo> orderedUserVos=new ArrayList<UserVo>();
		String userId="";
		//筛选出部门的主管对象
		if(userId.contains(",")) {
			String userIds[]=userId.split("|");
			for(UserVo u:users) {
				for(String uid:userIds) {
					if(uid.equals(u.getUserId())) {
						directors.add(u);
					}
				}
			}
		}else {
			for(UserVo u:users) {
				if(userId.equals(u.getUserId())) {
					directors.add(u);
				}
			}
		}
		return directors;
	}

	/**
	 *
	 * @description 根据部门id从内存中获取部门信息
	 * @author 徐亮
	 * @date 2019年5月6日 下午3:34:31
	 * @param deptId
	 * @return
	 * @return
	 * TOuterDept
	 */
	public TOrgDept getTOrgDept(String deptId) {
		Object obj = InitData.getInstance().getData().get("DEPT_DATA");
		if (obj != null) {
			Map<String,Object> deptD=(Map<String, Object>) obj;
			Object o = deptD.get("ALL_DEPT");
			List<TOrgDept> allDepts=(List<TOrgDept>) o;
			for(TOrgDept td:allDepts) {
				if(deptId.equals(td.getId())) {
					return td;
				}
			}
		}
		return null;
	}

	/**
	 *
	 * @description 根据用户类型，筛选用户
	 * @author 徐亮
	 * @date 2019年5月7日 下午1:52:10
	 * @param userType
	 * @param userTypes
	 * @param us
	 * @return
	 * @return
	 * List<UserVo>
	 */
	public List<UserVo> getUserVosByUserType(String userType,String userTypes[],List<UserVo> us){
		List<UserVo> uss=new ArrayList<UserVo>();
		if(us!=null) {
			//满足选择的用户类型的用户
			if(!StringUtils.isBlank(userType)) {
				if("0".equals(userType)) {
					//"0"表示查询所有类型的用户
					uss=us;
				}else if("1".equals(userType)){//表示查询除信通公司员工外所有外委人员
					for(int i=0;i<us.size();i++) {
						UserVo userVo=us.get(i);
						if(!("10000".equals(userVo.getUserType())) || StringUtils.isBlank(userVo.getUserType())) {
							uss.add(userVo);
						}
					}
				}else {
					for(int i=0;i<us.size();i++) {
						if (userType.contains(",")) {
							UserVo userVo=us.get(i);
							userTypes = userType.split(",");
							for(String ut:userTypes) {
								if(ut.equals(userVo.getUserType())) {
									uss.add(userVo);
								}
							}
						}else {
							UserVo userVo=us.get(i);
							if(userType.equals(userVo.getUserType())) {
								uss.add(userVo);
							}
						}
					}
				}
			}else {
				uss=us;
			}
		}
		return uss;
	}

	/**
	 * 获取信通公司人员列表,即：userType=10000
	 * @param userName
	 * @return
	 */
	@CrossOrigin
	@RequestMapping("/getXtgsUserList")
	@ResponseBody
	public ResultData getXtgsUserList(HttpServletRequest request,String userName, String userType){
		ResultData result = new ResultData();
		User user = new User();
		try{
			user = this.getLoginUserInfo(request);
			if(user == null || StringUtil.isNullOrEmpty(user.getPrivateIdentityId())){
				result.setErrorMsg("获取当前登录人失败");
				result.setSuccess(false);
				return result;
			}
		}catch (Exception e){
			e.printStackTrace();
			result.setSuccess(false);
			result.setErrorMsg("获取当前登录人失败");
			return result;
		}
		List<UserDetailVo> users=new ArrayList<UserDetailVo>();
		try {
//			if(StringUtils.isBlank(userName)){
//				userName = "王";
//			}
//			users = tOuterUserService.getUserListByUserType(userName,userType);
			users = tEmpBaseInfoService.getEmpBaseInfoByOrgId(userName);
			result.setSuccess(true);
			result.setData(users);
		} catch (Exception e) {
			result.setErrorMsg("系统问题，请联系管理员！");
			result.setSuccess(false);
			e.printStackTrace();
		}
		return result;
	}


	
}
